import datetime
import json
from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View

from home.models import House
from order.models import Order
from ihome.utils.response_code import RETCODE


class CommentOrder(LoginRequiredMixin,View):

    def put(self, request, order_id):
        """评价订单"""
        # 获取用户id
        user_id = request.session.get("user_id")
        # user_id = 2
        # 获取参数
        req_data = json.loads(request.body.decode())
        comment = req_data.get("comment")

        if not comment:
            return http.JsonResponse({'errno':RETCODE.PARAMERR,'errmsg':'参数错误'})

        # 根据订单编号检验该订单是自己下的订单,并且处于带评论的状态,否则不允许评论
        try:
            order = Order.objects.filter(id=order_id, user_id=user_id,status=3).first()
            house = order.house
        except Exception :
            return http.JsonResponse({'errno':RETCODE.DBERR,'errmsg':'无法获取订单数据'})

        if not order:
            return http.JsonResponse({'errno':RETCODE.NODATAERR,'errmsg':'无法操作'})

        # 保存评论
        try:
            # 修改订单状态为"已完成"
            order.status = 4
            # 添加评论内容
            order.comment = comment
            # 房子表中该房子订单数量+１
            house.order_count += 1
            # 提交

            order.save()
            house.save()
        except Exception:
            return http.JsonResponse({'errno':RETCODE.DBERR , 'errmsg': '保存失败'})

            # try:
            #     redis_store.delete("house_info_%s" % order.house.id)
            # except Exception as e:
            #     current_app.logger.error(e)
        return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': 'OK'})





class AcceptRejectOrder(LoginRequiredMixin,View):

    def put(self,request,order_id):
        """接单、拒单"""
        # 获取用户id
        user_id = request.session.get('user_id')
        user_id = 1

        # 获取参数
        req_data = json.loads(request.body.decode())
        # 校验参数
        if not req_data:
            return http.JsonResponse({'errno':RETCODE.PARAMERR,'errmsg':'参数错误'})
        # action参数表明用户客户端请求的是接单还是拒单的行为
        action = req_data.get('action')
        if action not in("accept", "reject"):
            return http.JsonResponse({'errno':RETCODE.PARAMERR,'errmsg':'参数错误'})

        try:
            # 根据订单号查询订单，并且要求订单处于等待接单状态
            order = Order.objects.filter(id=order_id,status=0)[0]
            house = order.house
        except Exception :
            return http.JsonResponse({'errno':RETCODE.DBERR,'errmsg':'无法获取订单数据'})

        # 确保房东只能修改属于自己房子的订单
        if not order or house.user_id != user_id:
            return http.JsonResponse({'errno':RETCODE.DBERR,'errmsg':'操作无效'})

        if action == 'accept':
            # 接单,将订单状态设置为等待评价
            order.status=3
        elif action == 'reject':
            # 拒单,要求用户传递拒单原因
            reason = req_data.get('reason')
            if not reason:
                return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '参数错误'})
            order.status =6
            order.comment = reason
        order.save()
        return http.JsonResponse({'errno':RETCODE.OK, 'errmsg': 'OK'})


class OrderView(LoginRequiredMixin,View):

    def get(self, request):
        """我的订单"""
        # 接收用户id
        user_id = request.session.get('user_id')
        # user_id = 1

        # 判断用户身份
        role = request.GET.get('role','')

        # 查询订单信息
        try:
            if role == 'landlord':
                # 以房东的身份查询订单,先查询属于自己的房子有那些
                houses = House.objects.filter(user_id=user_id)
                housers_ids = [house.id for house in houses]
                # 再查询预定了自己房子的订单
                orders = Order.objects.filter(house_id__in = housers_ids).order_by('-create_time')
            else:
                orders = Order.objects.filter(user_id=user_id).order_by('-create_time')
                print(orders)
        except Exception as e:
            return http.JsonResponse({'errno':RETCODE.DBERR,'errmsg':'查询订单信息失败'})
        """
        "data": {
        "orders": [
            {
                "amount": 1000,
                "comment": "哎哟不错哟",
                "ctime": "2017-11-14 09:59:35",
                "days": 2,
                "end_date": "2017-11-15",
                "img_url": "http://oyucyko3w.bkt.clouddn.com/FhgvJiGF9Wfjse8ZhAXb_pYObECQ",
                "order_id": 1,
                "start_date": "2017-11-14",
                "status": "COMPLETE",
                "title": "555"
            },
        """
        # 将订单信息转换为字典数据
        orders_dict_list =[]
        if orders:
            for order in orders:
                house_id=order.house_id
                try:
                    house= House.objects.get(id=house_id)
                except Exception:
                    return http.JsonResponse({"errno":RETCODE.DBERR,"errmsg":"未知错误"})

                orders_dict_list.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "img_url":"http://oyucyko3w.bkt.clouddn.com/"+ house.index_image_url,
                    "days": order.days,
                    "end_date": order.end_date,
                    "order_id": order.id,
                    "start_date":order.begin_date,
                    "status": order.status,
                    "title": house.title
                })
        return http.JsonResponse({'errno':RETCODE.OK,'errmsg':'OK',"data":{'orders':orders_dict_list}})


    def post(self,request):
        """房间预定"""
        # 判断用户是否登录

        # 接收参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date_str = json_dict.get('start_date')
        end_date_str = json_dict.get('end_date')
        # user_id = json_dict.get('user_id')
        # 接收用户id
        user_id = request.session.get('user_id')

        # 判断参数是否齐全
        if not all([house_id, start_date_str, end_date_str]):
            return http.JsonResponse({'errno':RETCODE.PARAMERR, 'errmsg':"参数错误"})
        # 处理日期
        try:
            # 将接收的日期字符串转换成日期格式
            start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
            end_date =  datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
            assert start_date <= end_date

            # 计算预定的天数
            days = (end_date - start_date).days + 1
        except Exception as e:
            return http.JsonResponse({'errno':RETCODE.PARAMERR, 'errmsg':'日期格式错误'})

        # 查询房子是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return http.JsonResponse({'errno':RETCODE.DBERR, 'errmsg':'获取房屋信息失败'})

        if not house:
            return http.JsonResponse({'errno':RETCODE.DBERR, 'errmsg': '房子不存在'})

        # 预定的房屋是否是自己的
        if user_id == house.user_id:
            return http.JsonResponse({'errno':RETCODE.THROTTLINGERR, 'errmsg': '不能预定自己的房屋'})

        # 确保用户预定的时间内,房屋没有被别人下单
        try:
            # 查询时间冲突的订单数
            count = Order.objects.filter(house_id = house_id,begin_date__lte=end_date,end_date__gte=start_date).count()
            print(count)
        except Exception as e:
            return http.JsonResponse({'errno':RETCODE.DBERR, 'errmsg': '检查出错,请稍后再试'})

        if count:
            return http.JsonResponse({'errno':RETCODE.NODATAERR, 'errmsg': '房屋已被预定'})

        # 预定总额

        amount = days * house.price

        # 保存订单数据
        try:
            order=Order.objects.create(
                house_id=house_id,
                user_id=user_id,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=amount
            )
        except Exception as e:
            return http.JsonResponse({'errno':RETCODE.DBERR, 'errmsg': '保存订单失败'})

        return http.JsonResponse({"errno":RETCODE.OK, "errmsg":"OK","data":{"order_id":order.id}})




